package com.example.RemindMe;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import java.util.List;

public class AlarmActivity extends Activity {

	MediaPlayer mMediaPlayer;
	int id;
	SharedPreferences sharedPreferences;
	SensorManager sensorManager;
	Sensor accelerometerSensor;
	boolean accelerometerPresent;
	private static boolean phoneTurned = false;
	float[] Ra = new float[16];
	float[] orientationValues = new float[3];
	private float zValue, yValue;
	// long thresholdEvent = 1000000;
	// long thresholdEvent = 500000;
	//long thresholdEvent = 1000000;
	long thresholdEvent = 0;
	long tsLastEvent = 0;
	boolean usedMethod = false;
	TextView alarmText;
	Vibrator v;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/**
		 * 
		 * Einschalten des Bildschirms sowie Aufheben des Lockscreens da der
		 * Lagesensor sonst teilweise nicht funktioniert.
		 * 
		 */
		v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		final Window win = getWindow();
		win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
				| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
		win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
				| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

		super.setRequestedOrientation(1);
		setContentView(R.layout.alarm);
		sensorManager.getOrientation(Ra, orientationValues);
		zValue = 0;
		yValue = 0;

		// final PowerManager pm = (PowerManager)
		// getSystemService(Context.POWER_SERVICE);
		// WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK,
		// "TAG");
		// wl.acquire();

		Bundle extras = getIntent().getExtras();
		id = extras.getInt("id");
		sharedPreferences = getSharedPreferences("alarms", 0);
		alarmText = (TextView) findViewById(R.id.textView1);
		String[] alarmT = sharedPreferences.getString(""+id,"0").split(";");
		alarmText.setText(alarmT[1]);
		System.out.println(id);
		playSound();

		/**
		 * 
		 * Initialisieren des SensorManagers
		 * 
		 */
		sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		List<Sensor> sensorList = sensorManager
				.getSensorList(Sensor.TYPE_ACCELEROMETER);
		if (sensorList.size() > 0) {
			accelerometerPresent = true;
			accelerometerSensor = sensorList.get(0);

		} else {
			accelerometerPresent = false;

		}

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (accelerometerPresent) {
			sensorManager.registerListener(accelerometerListener,
					accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
		}
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if (accelerometerPresent) {
			sensorManager.unregisterListener(accelerometerListener);
		}
	}

	/**
	 * 
	 * Listener f�r Lagesensor hinzuf�gen
	 * 
	 */
	private SensorEventListener accelerometerListener = new SensorEventListener() {

		public void onAccuracyChanged(Sensor arg0, int arg1) {
			// TODO Auto-generated method stub

		}

		public void onSensorChanged(SensorEvent arg0) {
			// TODO Auto-generated method stub
			float x_value = arg0.values[0];
			float y_value = arg0.values[1];
			float z_value = arg0.values[2];
			

			/**
			 * 
			 * Berechnungen, wann Handy gedreht wurde f�r Snooze-Funktion
			 * 
			 */

			float diffY = yValue - y_value;
			if (diffY < 0)
				diffY *= -1;

			float diff = zValue - z_value;
			if (diff < 0)
				diff *= -1;
			System.out.println(x_value);
			System.out.println(diffY);
			
			if (arg0.timestamp > tsLastEvent + thresholdEvent && usedMethod == false) {
				tsLastEvent = arg0.timestamp;

				//if ((x_value > 9 || x_value < -9) && diffY < 1) {
				if ((x_value > 9 || x_value < -9) && y_value < 3) {
					usedMethod = true;
					snooze();
				}

			}

		}

	};

	public void snooze(View v) {
		snooze();

	}

	/**
	 * 
	 * Snooze-Funktion zum Stoppen des Alarms und "neu anlegen" desselben.
	 * 
	 */
	public void snooze() {

		mMediaPlayer.stop();
		stopAlarm();

		Intent intent = new Intent(this, AlarmReceiver.class);
		intent.putExtra("id", id);
		PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);

		AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
		am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
				+ (getSnoozeDuration() * 60 * 1000), sender);

		AlarmAlertWakeLock.releaseCpuLock();
		usedMethod = false;
		finish();

	}

	public void stopAlarm(View v) {
		stopAlarm();
	}

	/**
	 * 
	 * Stoppen des Alarms
	 * 
	 */
	public void stopAlarm() {
		mMediaPlayer.stop();
		// Alle Alarm Manager mit Referenz 0 l�schen!!!
		Intent intent1 = new Intent(this, AlarmReceiver.class);
		PendingIntent sender1 = PendingIntent
				.getBroadcast(this, id, intent1, 0);
		AlarmManager am1 = (AlarmManager) getSystemService(ALARM_SERVICE);
		am1.cancel(sender1);
		v.cancel();
		finish();
	}

	/**
	 * 
	 * Abspielen eines voreingestellten Sounds, wird aufgerufen, wenn die
	 * Activity gestartet wird.
	 * 
	 */
	public void playSound() {

		String dataString = sharedPreferences.getString("" + id, "0");
		String[] alarmData = dataString.split(";");
		String uriString = alarmData[2];
		System.out.println(uriString);
		Uri uri = Uri.parse(uriString);
		
		mMediaPlayer = new MediaPlayer();
		try {
			mMediaPlayer.setDataSource(this, uri);
			mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
			mMediaPlayer.setLooping(true);
			mMediaPlayer.prepare();
			mMediaPlayer.start();
		} catch (Exception e) {

		}
		long[] pattern = {0, 100, 1000};
		v.vibrate(pattern, 0);
	}

	public void playSound(View v) {
		playSound();
	}

	/**
	 * 
	 * Methode um die Snooze-Dauer aus den SharedPreferences zu bekommen.
	 * 
	 */
	public int getSnoozeDuration() {

		String dataString = sharedPreferences.getString("" + id, "0");
		String[] alarmData = dataString.split(";");
		int snoozeDuration = 0;

		int snooze = Integer.parseInt(alarmData[3]);

		if (snooze == 0) {
			snoozeDuration = 1;
		}

		if (snooze == 1) {
			snoozeDuration = 3;
		}

		if (snooze == 2) {
			snoozeDuration = 5;
		}

		if (snooze == 3) {
			snoozeDuration = 10;
		}

		if (snooze == 4) {
			snoozeDuration = 15;
		}

		return snoozeDuration;
	}

}
